package com.hp.bon.sgw.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.Gson;
import com.hp.bon.sgw.Constants.NodeType;
import com.hp.bon.sgw.bean.SGWStatCapaBean;
import com.hp.bon.sgw.bean.SGWStatMessageBean;
import com.hp.bon.sgw.bean.SGWStatThruputBean;
import com.hp.bon.sgw.bean.bossnm.BossnmEventBean;
import com.hp.bon.sgw.bean.bossnm.BossnmKeyTop100Bean;
import com.hp.bon.sgw.bean.bossnm.BossnmParam;
import com.hp.bon.sgw.bean.bossnm.BossnmPerformanceBean;
import com.hp.bon.sgw.bean.bossnm.BossnmProcessLog;
import com.hp.bon.sgw.bean.bossnm.BossnmRequestMsgBean;
import com.hp.bon.sgw.bean.bossnm.BossnmWarnBean;
import com.hp.bon.sgw.domain.BusinessRecord;
import com.hp.bon.sgw.domain.MsgTransRecord;
import com.hp.bon.sgw.domain.Node;
import com.hp.bon.sgw.domain.ProcessLog;
import com.hp.bon.sgw.domain.Top100KeyWordBean;
import com.hp.bon.sgw.util.Comutils;
import com.hp.bon.sgw.util.dcc.DccAvpHelper;

public class DataStatusService
{
  private static final Logger logger = LoggerFactory.getLogger(DataStatusService.class);

  public final SGWStatThruputBean dccThruptBean = new SGWStatThruputBean("DCC");
  public int compareFileIntervalSeconds;
  public String compareFilePath;
  public int compareFileSecquence;
  public long compareFileLastTime;
  private SessionFactory outersessionFactory;

  @Transactional
  public void genarateCompareFile(String compareFilePath)
  {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(5, calendar.get(5) - 1);
    List<Node> nodeList = this.outersessionFactory.getCurrentSession().createQuery(" from Node ").list();
    Map nodeMap = ConfigService.id2NodeMap;
    for (Node n : nodeList) {
      nodeMap.put(Integer.valueOf(n.getId()), n);
    }
    genCompareA(compareFilePath, calendar, nodeMap);
    genCompareB(compareFilePath, calendar, nodeMap);
  }

  private void genCompareA(String compareFilePath, Calendar calendar, Map<Integer, Node> nodeMap)
  {
    String date = Comutils.formatTime(calendar.getTimeInMillis(), "yyyyMMdd");
    String hql = "select r from BusinessRecord r where r.requestTime >= :startTime and r.requestTime <= :endTime order by r.requestTime";
    Query query = this.outersessionFactory.getCurrentSession().createQuery(hql);
    query.setParameter("startTime", new Timestamp(Comutils.getStartTimeOfDay(calendar)));
    query.setParameter("endTime", new Timestamp(Comutils.getEndTimeOfDay(calendar)));
    List<BusinessRecord> list = query.list();
    Map<String,List> map = new HashMap<String,List>();
    List sublist = null;
    Node send_node = null;
    String send_key = "";
    Node recv_node = null;
    String recv_key = "";
    List messageIds = new ArrayList();
    for (BusinessRecord r : list) {
      messageIds.add(r.getSessionId());
      send_node = (Node)nodeMap.get(Integer.valueOf(r.getFromNodeId()));
      recv_node = (Node)nodeMap.get(Integer.valueOf(r.getToNodeId()));
      if ((send_node != null) && (send_node.getNodeType() != 1)) {
        send_key = "A_" + send_node.getNodeCode() + "_IN";
        sublist = (List)map.get(send_key);
        if (sublist == null) {
          sublist = new ArrayList();
          map.put(send_key, sublist);
        }
        sublist.add(r);
      }
      if ((recv_node != null) && (recv_node.getNodeType() != 1)) {
        recv_key = "A_" + recv_node.getNodeCode() + "_OUT";
        sublist = (List)map.get(recv_key);
        if (sublist == null) {
          sublist = new ArrayList();
          map.put(recv_key, sublist);
        }
        sublist.add(r);
      }
    }
    FileWriter fw = null;
    for (Entry entry : map.entrySet()) {
      String key = (String)entry.getKey();
      String fileName = "SGW_" + key + "_" + date + "_00001" + ".audit";
      try {
        fw = new FileWriter(compareFilePath + File.separator + fileName);
        fw.write(date + "|" + ((List)entry.getValue()).size());
        processRecord(nodeMap, fw, entry);
        logger.info("writer file " + fileName);
      } catch (IOException e) {
        logger.error("writer " + fileName + " error,error info :" + e);

        if (fw != null)
          try {
            fw.close();
          } catch (IOException e1) {
            logger.error("close FileWriter error.");
          }
      }
      finally
      {
        if (fw != null)
          try {
            fw.close();
          } catch (IOException e) {
            logger.error("close FileWriter error.");
          }
      }
    }
  }

  private void genCompareB(String compareFilePath, Calendar calendar, Map<Integer, Node> nodeMap)
  {
    String date = Comutils.formatTime(calendar.getTimeInMillis(), "yyyyMMdd");
    Map ccaMap = new HashMap();
    String hql = "select d from MsgTransRecord d where msgTime >= :startTime and msgTime <= :endTime and msgType in :msgTypes order by msgTime";
    Query query = this.outersessionFactory.getCurrentSession().createQuery(hql);
    query.setParameter("startTime", new Timestamp(Comutils.getStartTimeOfDay(calendar)));
    query.setParameter("endTime", new Timestamp(Comutils.getEndTimeOfDay(calendar)));
    query.setParameterList("msgTypes", new String[] { "CCR", "CCA" });
    List<MsgTransRecord> dccList = query.list();
    for (MsgTransRecord d : dccList) {
      if (d.getMsgType().equals("CCA")) {
        ccaMap.put(d.getSessionID(), d);
      }
    }
    Node send_node = null;
    String send_key = "";
    Node recv_node = null;
    String recv_key = "";
		Set<String> record_in = null;
		Set<String> record_out = null;
		Map<String, Set<String>> bMap = new HashMap<String, Set<String>>();
    StringBuilder sb = null;
    MsgTransRecord cca = null;
    for (MsgTransRecord d : dccList) {
      send_node = (Node)nodeMap.get(Integer.valueOf(d.getSendNodeId()));
			if (send_node.getNodeType() == NodeType.NODE_SR && d.getMsgType().equals(MsgTransRecord.MSG_TYPE_CCR)) {
        send_key = "B_" + send_node.getNodeCode() + "_OUT";
				record_out = bMap.get(send_key);
        if (record_out == null) {
          record_out = new HashSet();
          bMap.put(send_key, record_out);
        }
        sb = new StringBuilder();
        sb.append(d.getSessionID()).append("|");
        sb.append(send_node.getNECode()).append("|");
        sb.append(send_node.getNodeCode()).append("|");
        sb.append(Comutils.formatTime(d.getMsgTime().getTime(), "yyyyMMddhhmmssSSS")).append("|");
        cca = (MsgTransRecord)ccaMap.get(d.getSessionID());
        if (cca == null) {
          sb.append("||");
        } else {
          sb.append(Comutils.formatTime(cca.getMsgTime().getTime(), "yyyyMMddhhmmssSSS")).append("|");
          sb.append(cca.getResultCode());
        }
        record_out.add(sb.toString());
      }
      recv_node = (Node)nodeMap.get(Integer.valueOf(d.getReceiveNodeId()));
      if ((recv_node.getNodeType() == 1) && (d.getMsgType().equals("CCR"))) {
        recv_key = "B_" + send_node.getNodeCode() + "_IN";
        record_in = (Set)bMap.get(send_key);
        if (record_in == null) {
          record_in = new HashSet();
          bMap.put(recv_key, record_in);
        }
        sb = new StringBuilder();
        sb.append(d.getSessionID()).append("|");
        sb.append(send_node.getNECode()).append("|");
        sb.append(send_node.getNodeCode()).append("|");
        sb.append(Comutils.formatTime(d.getMsgTime().getTime(), "yyyyMMddhhmmssSSS")).append("|");
        cca = (MsgTransRecord)ccaMap.get(d.getSessionID());
        if (cca == null) {
          sb.append("||");
        } else {
          sb.append(Comutils.formatTime(cca.getMsgTime().getTime(), "yyyyMMddhhmmssSSS")).append("|");
          sb.append(cca.getResultCode());
        }
        record_in.add(sb.toString());
      }
    }
    FileWriter fw = null;
		for (Entry<String, Set<String>> entry : bMap.entrySet()) {
      String fileName = "SGW_" + (String)entry.getKey() + "_" + date + "_00001" + ".audit";
      try {
        fw = new FileWriter(compareFilePath + File.separator + fileName);
        fw.write(date + "|" + ((Set)entry.getValue()).size());
				for (String r : entry.getValue()) {
          fw.write("\r\n" + r);
        }
        logger.info("writer file " + fileName);
      } catch (IOException e) {
        logger.error("writer " + fileName + " error,error info :" + e);

        if (fw != null)
          try {
            fw.close();
          } catch (IOException e1) {
            logger.error("close FileWriter error.");
          }
      }
      finally
      {
        if (fw != null)
          try {
            fw.close();
          } catch (IOException e) {
            logger.error("close FileWriter error.");
          }
      }
    }
  }

  private void processRecord(Map<Integer, Node> nodeMap, FileWriter fw, Map.Entry<String, List<BusinessRecord>> entry) throws IOException
  {
    StringBuilder sb = null;
    for (BusinessRecord r : entry.getValue()) {
      sb = new StringBuilder();
      sb.append("\r\n" + r.getSessionId()).append("|");
      sb.append(((Node)nodeMap.get(Integer.valueOf(r.getFromNodeId()))).getNECode()).append("|");
      sb.append(((Node)nodeMap.get(Integer.valueOf(r.getFromNodeId()))).getNodeCode()).append("|");
      sb.append(r.getProtocolType()).append("|");
      if (r.getRequestTime() != null) {
        sb.append(Comutils.formatTime(r.getRequestTime().getTime(), "yyyyMMddhhmmssSSS"));
      }
      sb.append("|");
      if (r.getResponseTime() != null) {
        sb.append(Comutils.formatTime(r.getResponseTime().getTime(), "yyyyMMddhhmmssSSS"));
      }
      sb.append("|");
      sb.append(r.getResultCode()).append("|").append(r.getResultReason());
      fw.write(sb.toString());
    }
  }

  @Transactional
  public SGWStatMessageBean statMessage(Integer nodeId, Timestamp startTime)
  {
    SGWStatMessageBean bean = new SGWStatMessageBean();
    String hql = "select result, count(*) from BusinessRecord r where r.requestTime >= :startTime";
    hql = hql + " group by result";
    Query query = this.outersessionFactory.getCurrentSession().createQuery(hql);
    query.setParameter("startTime", startTime);
    long sum_cnt = 0L;
		List<Object[]> list = query.list();
    for (Object[] br : list) {
      int result_code = ((Integer)br[0]).intValue();
      long cnt = ((Long)br[1]).longValue();
      sum_cnt += cnt;
      switch (getErrorType(result_code)) {
      case 0:
        bean.setAnswerSuccess(bean.getAnswerSuccess() + cnt);
        break;
      case 1:
        bean.setRequestTimeout(bean.getRequestTimeout() + cnt);
        break;
      case 2:
        bean.setCapaAuthFail(bean.getCapaAuthFail() + cnt);
        break;
      case 3:
        bean.setTransferFail(bean.getTransferFail() + cnt);
        break;
      case 4:
        bean.setTransmitFail(bean.getTransmitFail() + cnt);
        break;
      case 5:
        bean.setAuthFail(bean.getAuthFail() + cnt);
        break;
      case 6:
        bean.setSrRouteFail(bean.getSrRouteFail() + cnt);
        break;
      default:
        bean.setOtherFail(bean.getOtherFail() + cnt);
      }
    }
    bean.setRequests(sum_cnt);
    bean.setAnswerFail(bean.getAuthFail() + bean.getCapaAuthFail() + bean.getTransferFail() + bean.getTransmitFail() + bean.getSrRouteFail() + bean.getOtherFail());
    bean.setAnswerSuccess(bean.getRequests() - bean.getRequestTimeout() - bean.getAnswerFail());
    return bean;
  }

  private static int getErrorType(int errorCode)
  {
    Integer type = Integer.valueOf(-1);

    Integer[] capaAuthFailArr = { Integer.valueOf(11001), Integer.valueOf(11002), Integer.valueOf(11003), Integer.valueOf(11004), Integer.valueOf(11005), Integer.valueOf(11006), 
      Integer.valueOf(11034) };

    Integer[] transferFailArr = { Integer.valueOf(11104), Integer.valueOf(11105), Integer.valueOf(11106), Integer.valueOf(11108), Integer.valueOf(11107) };

    List requestTimeout = Arrays.asList(new Integer[] { Integer.valueOf(-1), Integer.valueOf(11205), Integer.valueOf(11203) });
    List capaAuthFail = Arrays.asList(capaAuthFailArr);
    List transferFail = Arrays.asList(transferFailArr);

    List transmitFail = Arrays.asList(new Integer[] { Integer.valueOf(11202), Integer.valueOf(11204), Integer.valueOf(11201) });

    List authFail = Arrays.asList(new Integer[] { Integer.valueOf(11101) });

    List srRouteFail = Arrays.asList(new Integer[] { Integer.valueOf(3002) });
    Map<Integer,List> map = new HashMap<Integer,List>();
    map.put(Integer.valueOf(0), Arrays.asList(new Integer[] { Integer.valueOf(0), Integer.valueOf(2001) }));
    map.put(Integer.valueOf(1), requestTimeout);
    map.put(Integer.valueOf(2), capaAuthFail);
    map.put(Integer.valueOf(3), transferFail);
    map.put(Integer.valueOf(4), transmitFail);
    map.put(Integer.valueOf(5), authFail);
    map.put(Integer.valueOf(6), srRouteFail);
    for (Map.Entry entry : map.entrySet()) {
      if (((List)entry.getValue()).contains(Integer.valueOf(errorCode))) {
        return ((Integer)entry.getKey()).intValue();
      }
    }
    return type.intValue();
  }

  @Transactional
  public void genarateBossnmRequsetMsg(String dataPath, BossnmParam reqMsgParam)
  {
    genarateBossnmMsg(dataPath, reqMsgParam, 1);
  }

  @Transactional(readOnly=true)
  public void genarateBossnmAskMsg(String dataPath, BossnmParam askMsgParam)
  {
    genarateBossnmMsg(dataPath, askMsgParam, 0);
  }

  private void genarateBossnmMsg(String dataPath, BossnmParam msgParam, int transDirection)
  {
    long endTime = msgParam.getEndTime();

    String hql = "select serviceContextId,requestHost,protocolType,count(*),sum(recvRequestLength) from BusinessRecord r where r.requestTime >= :startTime and r.requestTime < :endTime and r.result=0 and r.transDirection = :transDirection group by serviceContextId,requestHost,protocolType ";

    Query query = this.outersessionFactory.getCurrentSession().createQuery(hql);
    query.setParameter("startTime", new Timestamp(msgParam.getStatTime().getTimeInMillis()));
    query.setParameter("endTime", new Timestamp(endTime));
    query.setParameter("transDirection", Integer.valueOf(transDirection));
		List<Object[]> listSuccess = query.list();

    hql = "select serviceContextId,requestHost,protocolType,count(*),sum(recvRequestLength) from BusinessRecord r where r.requestTime >= :startTime and r.requestTime < :endTime and r.result !=0 and r.transDirection = :transDirection group by serviceContextId,requestHost, protocolType ";

    query = this.outersessionFactory.getCurrentSession().createQuery(hql);
    query.setParameter("startTime", new Timestamp(msgParam.getStatTime().getTimeInMillis()));
    query.setParameter("endTime", new Timestamp(endTime));
    query.setParameter("transDirection", Integer.valueOf(transDirection));
		List<Object[]> listError = query.list();
    String filename = msgParam.getFileName();
    String sattime = Comutils.formatTime(msgParam.getStatTime().getTimeInMillis(), "yyyyMMddHHmm");
		List<Object> contents = new ArrayList<Object>();
    BossnmRequestMsgBean bean = null;
    for (Object[] b : listSuccess) {
      bean = new BossnmRequestMsgBean((String)b[0], (String)b[1], ((Integer)b[2]).intValue(), ((Long)b[3]).longValue(), ((Long)b[4]).longValue(), 0, sattime);
      contents.add(bean);
    }
    for (Object[] b : listError) {
      bean = new BossnmRequestMsgBean((String)b[0], (String)b[1], ((Integer)b[2]).intValue(), ((Long)b[3]).longValue(), ((Long)b[4]).longValue(), 1, sattime);
      contents.add(bean);
    }
    writeJsonFile(dataPath + File.separator + filename, contents);
    msgParam.setStatTime(endTime);
  }

  @Transactional(readOnly=true)
  public List<SGWStatCapaBean> getAccessedCapabilities(Timestamp startTime)
  {
    List capBeans = new LinkedList();
    String hsql = "select r.serviceContextId , r.requestHost  from BusinessRecord r where r.requestTime > :startTime group by serviceContextId, requestHost";
    Query query = this.outersessionFactory.getCurrentSession().createQuery(hsql);
    query.setParameter("startTime", startTime);
    List<Object[]> lists = query.list();
		Map<String, Set<String>> caps = new HashMap<String, Set<String>>();
		for (Object[] row : lists) {
			String cap = (String) row[0];
			String userName = (String) row[1];
			if (cap.contains("@")) {
				cap = DccAvpHelper.getCapability(cap);
			}
			Set<String> userSets = caps.get(cap);
			if (userSets == null) {
				userSets = new LinkedHashSet<String>();
				caps.put(cap, userSets);
			}
			if (!userSets.contains(userName)) {
				userSets.add(userName);
			}

		}
		for (Map.Entry<String, Set<String>> userCapEntry : caps.entrySet()) {
			String cap = userCapEntry.getKey();
			for (String neHost : userCapEntry.getValue()) {
				SGWStatCapaBean capaBean = new SGWStatCapaBean();
				capaBean.setCapaInfo(cap);
				capaBean.setHostID(neHost);
				capBeans.add(capaBean);
			}
		}

    return capBeans;
  }

  public void genarateKeyTop100(String dataPath, String srcDataPath, BossnmParam top100Param)
  {
    Calendar time = Calendar.getInstance();
    time.setTimeInMillis(System.currentTimeMillis());
    time.set(5, time.get(5) - 1);
    String fileName = srcDataPath + File.separator + Top100KeyWordBean.class.getSimpleName() + "_" + Comutils.formatTime(time.getTimeInMillis(), "yyyyMMdd") + ".json";
    Map<String,BossnmKeyTop100Bean> map = new HashMap<String,BossnmKeyTop100Bean>();
    BossnmKeyTop100Bean bossBean = null;
    BufferedReader reader = null;
    try {
      reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
      String line = reader.readLine();
      while ((line != null) && (!"".equals(line))) {
        Top100KeyWordBean topBean = (Top100KeyWordBean)new Gson().fromJson(line, Top100KeyWordBean.class);
        bossBean = (BossnmKeyTop100Bean)map.get(topBean.getKey());
        if (bossBean == null) {
          bossBean = new BossnmKeyTop100Bean();
          bossBean.setAVP_NAME(topBean.getMonitorKey());
          bossBean.setAVP_VALUE(topBean.getKeyContent());
          bossBean.setMSG_TYPE(getMsgType(topBean.getProtocolType()));
          bossBean.setSERVICE_CONTEXT_ID(topBean.getServiceContextId());
          bossBean.setSTAT_TIME(Comutils.formatTime(time.getTimeInMillis(), "yyyyMMdd") + "0000");
          map.put(topBean.getKey(), bossBean);
        }
        bossBean.incMSG_CNT();
        line = reader.readLine();
      }
      if (!map.isEmpty()) {
        String bossFileName = top100Param.getFileName();
        List contents = new ArrayList();
        for (Map.Entry e : map.entrySet()) {
          contents.add(e.getValue());
        }
        writeJsonFile(dataPath + File.separator + bossFileName, contents);
      }
    } catch (FileNotFoundException e) {
      logger.warn("there is no KeyTop100 file lastday! " + fileName);
    } catch (IOException e) {
      logger.warn("101|read KeyTop100 file IO error!");
    } catch (Exception e) {
      logger.warn("101|read KeyTop100 file error!");
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          logger.warn("close reader err.");
        }
      }
      top100Param.setStatTime(top100Param.getEndTime());
    }
  }

  @Transactional
  public void genarateBossnmProcessLog(String dataPath, BossnmParam processParam, BossnmParam eventParam, BossnmParam warnParam)
  {
    long endTime = processParam.getEndTime();
    String hql = "select l from ProcessLog l where logTime >= :startTime and logTime < :endTime order by logTime";
    Query query = this.outersessionFactory.getCurrentSession().createQuery(hql);
    query.setParameter("startTime", new Timestamp(processParam.getStatTime().getTimeInMillis()));
    query.setParameter("endTime", new Timestamp(endTime));
    List<ProcessLog> logs = query.list();
    List list = new ArrayList();
    BossnmProcessLog blog = null;
    BossnmEventBean eventBean = null;
    BossnmWarnBean warnBean = null;
    Map eventMap = new HashMap();
    Map warnMap = new HashMap();
    for (ProcessLog l : logs) {
      blog = new BossnmProcessLog();
      blog.setLOG_GRADE(l.getLogLevel());
      blog.setERROR_CODE(l.getErrorCode()+"");
      blog.setERROR_NAME(l.getErrorName());
      blog.setEXPERT_ADVICE(l.getExpertAdvice());
      blog.setLOG_BORN_TIME(Comutils.formatTime(l.getLogTime().getTime(), "yyyyMMddHHmmss"));
      list.add(blog);
      if (l.getLogType().equals("StatusChange")) {
        if (BossnmEventBean.KPIMap.get(Integer.valueOf(l.getErrorCode())) != null) {
          eventBean = (BossnmEventBean)eventMap.get(BossnmEventBean.KPIMap.get(Integer.valueOf(l.getErrorCode())));
          if (eventBean == null) {
            eventBean = new BossnmEventBean((String)BossnmEventBean.KPIMap.get(Integer.valueOf(l.getErrorCode())));
            eventBean.setFirstTime(Comutils.formatTime(l.getLogTime().getTime(), "yyyyMMddHHmmss"));
            eventBean.setNotifyID(Comutils.formatTime(System.currentTimeMillis(), "yyyyMMddHHmmssSSS"));
            eventBean.setKBP("/SGW");
            eventBean.setEvent(l.getContent());
            eventMap.put((String)BossnmEventBean.KPIMap.get(Integer.valueOf(l.getErrorCode())), eventBean);
          }
          eventBean.incCount();
          eventBean.setLastTime(Comutils.formatTime(l.getLogTime().getTime(), "yyyyMMddHHmmss"));
        }
        if (BossnmWarnBean.KPIMap.get(Integer.valueOf(l.getErrorCode())) != null) {
          warnBean = (BossnmWarnBean)warnMap.get(BossnmWarnBean.KPIMap.get(Integer.valueOf(l.getErrorCode())));
          if (warnBean == null) {
            warnBean = new BossnmWarnBean((String)BossnmWarnBean.KPIMap.get(Integer.valueOf(l.getErrorCode())));
            warnBean.setFirstTime(Comutils.formatTime(l.getLogTime().getTime(), "yyyyMMddHHmmss"));
            warnBean.setAlarmID(Comutils.formatTime(System.currentTimeMillis(), "yyyyMMddHHmmssSSS"));
            warnBean.setKBP("/SGW");
            warnBean.setEventLevel(2);
            warnBean.setEventState(10);
            warnMap.put((String)BossnmWarnBean.KPIMap.get(Integer.valueOf(l.getErrorCode())), warnBean);
          }
          warnBean.incCount();
          warnBean.setLastTime(Comutils.formatTime(l.getLogTime().getTime(), "yyyyMMddHHmmss"));
        }
      }
    }
    writeJsonFile(dataPath + File.separator + processParam.getFileName(), list);
    processParam.setStatTime(endTime);

    writeJsonFile(dataPath + File.separator + eventParam.getFileName(), eventMap.values());
    eventParam.setStatTime(endTime);

    writeJsonFile(dataPath + File.separator + warnParam.getFileName(), warnMap.values());
    warnParam.setStatTime(endTime);
  }

  @Transactional
  public void genarateBossnmMsgStat(String dataPath, BossnmParam param)
  {
    long endTime = param.getEndTime();
    String hql = "select serviceContextId,opType,substring(msgType,3,3),count(*),sum(msgLength) from MsgTransRecord r where r.msgTime >= :startTime and r.msgTime < :endTime  and r.serviceContextId not like '%Net-Ctrl%'and (sendNodeId in (select id from Node where nodeType = :nodeType) or receiveNodeId in (select id from Node where nodeType = :nodeType))group by serviceContextId,opType,substring(msgType,3,3)";

    Query query = this.outersessionFactory.getCurrentSession().createQuery(hql);
    query.setParameter("startTime", new Timestamp(param.getStatTime().getTimeInMillis()));
    query.setParameter("endTime", new Timestamp(endTime));
    query.setParameter("nodeType", Integer.valueOf(1));
    List<Object[]> list = query.list();
    BossnmPerformanceBean sendReqCountBean = new BossnmPerformanceBean("40-30-12-02-00-005", "recv request count");
    BossnmPerformanceBean sendReqSizeBean = new BossnmPerformanceBean("40-30-12-02-00-006", "recv request size");
    BossnmPerformanceBean sendAckCountBean = new BossnmPerformanceBean("40-30-12-02-00-007", "recv answer count");
    BossnmPerformanceBean sendAckSizeBean = new BossnmPerformanceBean("40-30-12-02-00-008", "recv answer size");
    BossnmPerformanceBean receiveReqCountBean = new BossnmPerformanceBean("40-30-12-02-00-001", "send request count");
    BossnmPerformanceBean receiveReqSizeBean = new BossnmPerformanceBean("40-30-12-02-00-002", "send request count");
    BossnmPerformanceBean receiveAckCountBean = new BossnmPerformanceBean("40-30-12-02-00-003", "send answer count");
    BossnmPerformanceBean receiveAckSizeBean = new BossnmPerformanceBean("40-30-12-02-00-004", "send answer size");
    String kbp = "";
    String opType = "";
    String msgType = "";
    long count = 0L;
    long size = 0L;
    List resultlist = new ArrayList();
    for (Object[] o : list) {
      kbp = "/SGW/" + (String)o[0];
      opType = (String)o[1];
      msgType = (String)o[2];
      count = ((Long)o[3]).longValue();
      size = ((Long)o[4]).longValue();
      if (opType.equals("send")) {
        if (msgType.equals("R")) {
          sendReqCountBean.setKBP(kbp);
          sendReqCountBean.setKBPName(kbp);
          sendReqCountBean.setAvg(count);
          sendReqCountBean.setMax(count);
          sendReqCountBean.setMin(count);

          sendReqSizeBean.setKBP(kbp);
          sendReqSizeBean.setKBPName(kbp);
          sendReqSizeBean.setAvg(size);
          sendReqSizeBean.setMax(size);
          sendReqSizeBean.setMin(size);
        } else if (msgType.equals("A")) {
          sendAckCountBean.setKBP(kbp);
          sendAckCountBean.setKBPName(kbp);
          sendAckCountBean.setAvg(count);
          sendAckCountBean.setMax(count);
          sendAckCountBean.setMin(count);

          sendAckSizeBean.setKBP(kbp);
          sendAckSizeBean.setKBPName(kbp);
          sendAckSizeBean.setAvg(size);
          sendAckSizeBean.setMax(size);
          sendAckSizeBean.setMin(size);
        }
      } else if (opType.equals("recv")) {
        if (msgType.equals("R")) {
          receiveReqCountBean.setKBP(kbp);
          receiveReqCountBean.setKBPName(kbp);
          receiveReqCountBean.setAvg(count);
          receiveReqCountBean.setMax(count);
          receiveReqCountBean.setMin(count);

          receiveReqSizeBean.setKBP(kbp);
          receiveReqSizeBean.setKBPName(kbp);
          receiveReqSizeBean.setAvg(size);
          receiveReqSizeBean.setMax(size);
          receiveReqSizeBean.setMin(size);
        }
        else if (msgType.equals("A")) {
          receiveAckCountBean.setKBP(kbp);
          receiveAckCountBean.setKBPName(kbp);
          receiveAckCountBean.setAvg(count);
          receiveAckCountBean.setMax(count);
          receiveAckCountBean.setMin(count);

          receiveAckSizeBean.setKBP(kbp);
          receiveAckSizeBean.setKBPName(kbp);
          receiveAckSizeBean.setAvg(size);
          receiveAckSizeBean.setMax(size);
          receiveAckSizeBean.setMin(size);
        }
      }
    }
    resultlist.add(sendReqCountBean);
    resultlist.add(sendReqSizeBean);
    resultlist.add(sendAckCountBean);
    resultlist.add(sendAckSizeBean);
    resultlist.add(receiveReqCountBean);
    resultlist.add(receiveReqSizeBean);
    resultlist.add(receiveAckCountBean);
    resultlist.add(receiveAckSizeBean);
    writeJsonFile(dataPath + File.separator + param.getFileName(), resultlist);
    param.setStatTime(endTime);
  }

  private static String getMsgType(int gatewaytype) {
    switch (gatewaytype) {
    case 1:
      return "CCR";
    case 2:
      return "SCR";
    case 3:
      return "SOAP";
    }
    return "unknow";
  }

  private void writeJsonFile(String fileName, Collection contents)
  {
    FileWriter fw = null;
    try {
      if (logger.isInfoEnabled()) {
        logger.info("Bossnm file: " + fileName);
      }
      fw = new FileWriter(fileName);
      for (Iterator localIterator = contents.iterator(); localIterator.hasNext(); ) { Object o = localIterator.next();
        fw.write(new Gson().toJson(o) + "\r\n"); }
    }
    catch (Exception e) {
      logger.warn("processlog|102|wirte file " + fileName + " failed");

      if (fw != null)
        try {
          fw.close();
        } catch (IOException e1) {
          logger.warn("close FileWriter error.");
        }
    }
    finally
    {
      if (fw != null)
        try {
          fw.close();
        } catch (IOException e) {
          logger.warn("close FileWriter error.");
        }
    }
  }

  @Autowired
  @Qualifier("outerSessionFactory")
  public void setSessionFactory(SessionFactory sessionFactory) {
    this.outersessionFactory = sessionFactory;
  }
}